import * as express from 'express';
import * as bodyParser from 'body-parser';
import { Request, Response } from 'express';
import { AppDataSource } from '@/data-source';
import { Routes } from '@/routes';
import { verifyToken } from '@/middleware/verify';
import { PORT } from '@/share/config';
import swaggerSpec from '@/middleware/swagger';
import * as session from 'express-session';
import {
  responseSuccess,
  responseError,
} from '@/share/interface/standard';
import InitDataSource from '@/middleware/initData';
import { moduleClickMiddleware } from '@/middleware/module';

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const cors = require('cors');
AppDataSource.initialize()
  .then(async () => {
    const app = express();

    // app.use(express.static('public'));
    app.use('/uploads',express.static('uploads'));

    app.use(
      session({
        secret: '__session_secret__',
        resave: false,
        saveUninitialized: true,
        cookie: {
          maxAge: 3600000, // 1小时过期
        },
      })
    );
    app.use(verifyToken);

    app.use(
      '/api/api-docs',
      swaggerUi.serve,
      swaggerUi.setup(swaggerSpec)
    );
    app.use(moduleClickMiddleware);

    app.use(
      cors({
        credentials: true,
      })
    );

    app.use(bodyParser.json({ limit: '15mb' }));
    app.use(bodyParser.urlencoded({ limit: '15mb', extended: true }));

    Routes.forEach((route) => {
      (app as any)[route.method](
        `/api${route.route}`,
        async (req: Request, res: Response, next: Function) => {
          try {
            const result = await new (route.controller as any)()[
              route.action
            ](req, res, next);
            if (result !== null && result !== undefined) {
              res.json(result);
            }
          } catch (error) {
            console.log(error);
            res.json(responseError(error + ''));
          }
        }
      );
    });

    const initData = new InitDataSource();
    await initData.initRole();
    await initData.initSymptom();

    app.listen(PORT);

    console.log(
      `服务已启动至端口\x1b[33m${PORT}\x1b[0m,点击 \x1b[34mhttp://localhost:${PORT}/api-docs\x1b[0m 查看接口文档`
    );
  })
  .catch((error) => console.log(error));
